<template>
  <div class="upload-file">
    <el-upload
      ref="upload"
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :headers="headers"
      :on-error="handleUploadError"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :show-file-list="true"
      class="upload-file-uploader"
    >
      <!-- 上传按钮 -->
      <el-button icon="el-icon-upload" size="mini" type="primary">附件上传</el-button>
      <!-- 上传提示 -->
      <div v-if="showTip" slot="tip" class="el-upload__tip">
        请上传
        <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
        <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b></template>
        的文件
      </div>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { deleteFile, getPreviewUrl } from '@/api/oss/minio'

export default {
  props: {
    // 值
    value: {
      type: Array,
      default: () => undefined
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 100
    },
    // 文件类型, () => ["doc", "xls", "ppt", "txt", "pdf"]
    fileType: {
      type: Array,
      default: () => undefined
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + '/minio/uploadFile', // 上传的服务器地址
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      fileList: []
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize)
    },
    // 列表
    list() {
      if (this.value && this.value.length > 0) {
        return this.value.map(item => {
          let res = { data: item.fileUrl }
          return {
            name: item.fileName,
            response: res,
            size: item.fileSize,
            uid: item.uid,
            attachId: item.attachId
          }
        })
      } else {
        return []
      }
    }
  },
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = ''
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true
          if (fileExtension && fileExtension.indexOf(type) > -1) return true
          return false
        })
        if (!isTypeOk) {
          this.$message.error(`文件格式不正确, 请上传${this.fileType.join('/')}格式文件!`)
          return false
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`)
          return false
        }
      }
      return true
    },
    // 删除文件
    handleRemove(file, fileList) {
      let objectName = file.response.data
      deleteFile(objectName).then(response => {
        this.$emit('fileEvent', this.dataFormat(fileList))
      })
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error('上传失败, 请重试')
    },
    // 上传成功回调
    handleUploadSuccess(res, file, fileList) {
      this.$message.success('上传成功')
      this.$emit('fileEvent', this.dataFormat(fileList))
    },
    // 预览文件
    handlePreview(file) {
      let objectName = file.response.data
      getPreviewUrl(objectName).then(response => {
        window.open(response.data)
      })
    },
    dataFormat(fileList) {
      if (!fileList || fileList.length === 0) {
        return []
      }
      let attaches = []
      fileList.forEach(item => {
        let attach = {}
        if (item.attachId) {
          attach.attachId = item.attachId
        }
        attach.fileName = item.name
        attach.fileUrl = item.response.data
        attach.fileExt = item.name.lastIndexOf('.') > -1 ? item.name.slice(item.name.lastIndexOf('.') + 1) : ''
        attach.fileSize = item.size
        attach.uid = item.uid
        attaches.push(attach)
      })
      return attaches
    }
  },
  watch: {
    value(newValue, oldValue) {
      this.fileList = this.list
    }
  },
  created() {
    this.fileList = this.list
  }
}
</script>

<style lang="scss" scoped>
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
